package com.zyw.controller.procurement;


import com.zyw.entity.*;
import com.zyw.enums.ManagermentSystemEnum;
import com.zyw.exception.ManagermentSystemException;
import com.zyw.from.ProcurementFrom;
import com.zyw.service.clothing.ClothingService;
import com.zyw.service.order.OrderClientService;
import com.zyw.service.order.OrderService;
import com.zyw.service.procurement.ProcurementMaterialAnalysisService;
import com.zyw.service.procurement.ProcurementOrdersService;
import com.zyw.service.procurement.ProcurementPurchaseOrdersService;
import com.zyw.service.repertory.RepertoryMaterialService;
import com.zyw.util.ProcurementOrdersUtil;
import com.zyw.util.ResultVOUtil;
import com.zyw.vo.LayUITableVO;
import com.zyw.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

import static com.zyw.constant.ManagermentSystemConstant.PROCUREMENT_MATERIAL_ANALYSIS_MAP;

@Controller
@Slf4j
@RequestMapping("/procurement/orders")
public class ProcurementOrdersController {


    @Autowired
    public OrderService orderService;

    @Autowired
    public ClothingService clothingService;

    @Autowired
    public OrderClientService orderClientService;

    @Autowired
    public ProcurementOrdersService procurementOrdersService;

    @Autowired
    public ProcurementMaterialAnalysisService procurementMaterialAnalysisService;

    @Autowired
    public RepertoryMaterialService repertoryMaterialService;

    @Autowired
    public ProcurementPurchaseOrdersService procurementPurchaseOrdersService;

    //菜品类别展示
    @GetMapping("/index")
    public String index(Model model){



        return "procurement/orders/index";

    }
    //获取菜品类别信息
    @GetMapping("/list")
    @ResponseBody
    public LayUITableVO<List<ProcurementOrders>> list (@RequestParam(defaultValue = "1") Integer page,
                                                       @RequestParam(defaultValue = "10") Integer limit,
                                                       ProcurementFrom from){

        Map<String ,Object> map = new HashMap<>();
        map.put("page",page);
        map.put("limit",limit);
        map.put("from",from);
        LayUITableVO< List<ProcurementOrders>> vo = procurementOrdersService.findPage(map);


        return vo;
    }

    //修改菜品类别信息1（查询指定id菜品分类详情）
    @GetMapping("/edit-ui")
    public String editUI(String id,Model model){

        Order order = orderService.selectById(id);
        List<Clothing> clothingList = clothingService.findAllIdAndName();
        List<OrderClient> orderClientList = orderClientService.findAllIdAndName();
        Map<String,List<RepertoryMaterial>> map = repertoryMaterialService.findProcurementOrder();

        ProcurementOrders procurementOrders = procurementOrdersService.selectById(id);

        model.addAttribute("order",order);
        model.addAttribute("clothingList",clothingList);
        model.addAttribute("orderClientList",orderClientList);
        model.addAttribute("procurementOrders",procurementOrders);

        model.addAttribute("map",map);
        return "procurement/orders/edit";

    }

    //获取菜品类别信息
    @GetMapping("/materialList")
    @ResponseBody
    public LayUITableVO<List<ProcurementMaterialAnalysis>> materialList (@RequestParam(defaultValue = "1") Integer page,
                                                       @RequestParam(defaultValue = "10") Integer limit,
                                                                 ProcurementFrom from){

        Map<String ,Object> map = new HashMap<>();
        map.put("page",page);
        map.put("limit",limit);
        map.put("from",from);
        LayUITableVO< List<ProcurementMaterialAnalysis>> vo = procurementMaterialAnalysisService.findPage(map);

        PROCUREMENT_MATERIAL_ANALYSIS_MAP.put(from.getOrderId()+from.getLiningType(),vo);

        return vo;
    }

    @PostMapping("/addMaterial")
    @ResponseBody
    public ResultVO addMaterial(ProcurementMaterialAnalysis procurementMaterialAnalysis){
        if (procurementMaterialAnalysis.getLiningNum() == null){
            return ResultVOUtil.error(88,"请输入物料数量");
        }
        LayUITableVO<List<ProcurementMaterialAnalysis>> listLayUITableVO = PROCUREMENT_MATERIAL_ANALYSIS_MAP.get(procurementMaterialAnalysis.getOrderId() + procurementMaterialAnalysis.getLiningType());

        List<ProcurementMaterialAnalysis> dataList = listLayUITableVO.getData();
        for (ProcurementMaterialAnalysis materialAnalysis : dataList) {
            if ((int)materialAnalysis.getLiningId() == (int)procurementMaterialAnalysis.getLiningId()){
                throw new ManagermentSystemException(ManagermentSystemEnum.FOOD_CATEGORY_ADD_REPETITION);
            }
        }

        RepertoryMaterial repertoryMaterial = repertoryMaterialService.selectById(String.valueOf(procurementMaterialAnalysis.getLiningId()));
        procurementMaterialAnalysis.setLiningPrice(repertoryMaterial.getPrice());
        procurementMaterialAnalysis.setLiningSubtotal(String.valueOf((procurementMaterialAnalysis.getLiningNum()*Double.valueOf(procurementMaterialAnalysis.getLiningPrice()))));
        procurementMaterialAnalysis.setLiningName(repertoryMaterial.getMaterialName());

        dataList.add(procurementMaterialAnalysis);

        return ResultVOUtil.ok();
    }

    //获取菜品类别信息
    @GetMapping("/materialRefresh")
    @ResponseBody
    public LayUITableVO<List<ProcurementMaterialAnalysis>> materialRefresh (@RequestParam(defaultValue = "1") Integer page,
                                                                         @RequestParam(defaultValue = "10") Integer limit,
                                                                         ProcurementFrom from){


        LayUITableVO<List<ProcurementMaterialAnalysis>> vo = PROCUREMENT_MATERIAL_ANALYSIS_MAP.get(from.getOrderId() + from.getLiningType());


        return vo;
    }

    @PostMapping("/delMaterial")
    @ResponseBody
    public ResultVO delMaterial(String id,String liningId,String liningType){
        LayUITableVO<List<ProcurementMaterialAnalysis>> listLayUITableVO = PROCUREMENT_MATERIAL_ANALYSIS_MAP.get(id +liningType);

        List<ProcurementMaterialAnalysis> dataList = listLayUITableVO.getData();

        for (ProcurementMaterialAnalysis materialAnalysis : dataList) {
           if ((int)materialAnalysis.getLiningId() ==(int)Integer.valueOf(liningId)){
               dataList.remove(materialAnalysis);
               break;
           }
        }
        procurementMaterialAnalysisService.delectBy(id,liningId);
        return ResultVOUtil.ok();
    }

    @PostMapping("/editMaterial")
    @ResponseBody
    public ResultVO editMaterial(ProcurementMaterialAnalysis procurementMaterialAnalysis){
        LayUITableVO<List<ProcurementMaterialAnalysis>> listLayUITableVO = PROCUREMENT_MATERIAL_ANALYSIS_MAP.get(procurementMaterialAnalysis.getOrderId() + procurementMaterialAnalysis.getLiningType());

        List<ProcurementMaterialAnalysis> dataList = listLayUITableVO.getData();

        for (ProcurementMaterialAnalysis materialAnalysis : dataList) {
            if ((int)materialAnalysis.getLiningId()== (int)procurementMaterialAnalysis.getLiningId()){
                materialAnalysis.setLiningNum(procurementMaterialAnalysis.getLiningNum());
                materialAnalysis.setLiningSubtotal(String.valueOf((materialAnalysis.getLiningNum()*Double.valueOf(materialAnalysis.getLiningPrice()))));
            }
        }

        return ResultVOUtil.ok();
    }

    //取消操作，删除map中的缓存
    @PostMapping("/delAllMap")
    @ResponseBody
    public ResultVO delAllMap (String id){


        Set<String> keySet = PROCUREMENT_MATERIAL_ANALYSIS_MAP.keySet();
        for (String s : keySet) {
            if (s.equals(id+0)){
                PROCUREMENT_MATERIAL_ANALYSIS_MAP.remove(id);
            }
            if (s.equals(id+1)){
                PROCUREMENT_MATERIAL_ANALYSIS_MAP.remove(id);
            }
        }


        return ResultVOUtil.ok();
    }

    //提交操作（修改或添加），判断订单详情的数据完整性，分别存入两表中，移除map缓存
    @PostMapping("/saveMap")
    @ResponseBody
    public ResultVO saveMap (String id,String principal,String principalDate){

        LayUITableVO<List<ProcurementMaterialAnalysis>> listLayUITableVO = PROCUREMENT_MATERIAL_ANALYSIS_MAP.get(id + 0);
        List<ProcurementMaterialAnalysis> data = listLayUITableVO.getData();

        procurementMaterialAnalysisService.save(data);

        LayUITableVO<List<ProcurementMaterialAnalysis>> listLayUITableVO1 = PROCUREMENT_MATERIAL_ANALYSIS_MAP.get(id + 1);
        List<ProcurementMaterialAnalysis> data1 = listLayUITableVO1.getData();
        procurementMaterialAnalysisService.save(data1);
        if (data.size()==0 && data1.size()==0){
            return ResultVOUtil.error(58,"该订单所需物料不能为空！请重新选择");
        }

        ProcurementOrders conversion = ProcurementOrdersUtil.conversion(id, data, data1);
        conversion.setPrincipal(principal);
        conversion.setPrincipalDate(principalDate);
        procurementOrdersService.save(conversion);


        return ResultVOUtil.ok();
    }


    //修改菜品类别信息1（查询指定id菜品分类详情）
    @GetMapping("/add-ui")
    public String addUI(Model model){

        List<Order> orderList = orderService.selectByStatus(1);
        List<Clothing> clothingList = clothingService.findAllIdAndName();
        List<OrderClient> orderClientList = orderClientService.findAllIdAndName();
        Map<String,List<RepertoryMaterial>> map = repertoryMaterialService.findProcurementOrder();




        model.addAttribute("orderList",orderList);
        model.addAttribute("clothingList",clothingList);
        model.addAttribute("orderClientList",orderClientList);
        model.addAttribute("principal","小红");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        model.addAttribute("principalDate",dateFormat.format(new Date()));


        model.addAttribute("map",map);
        return "procurement/orders/add";

    }


    //提交操作（修改或添加），判断订单详情的数据完整性，分别存入两表中，移除map缓存
    @PostMapping("/showMaterial")
    @ResponseBody
    public ResultVO showMaterial (String id){
        Order order = orderService.selectById(id);

        return ResultVOUtil.ok(order);
    }


    @PostMapping("/addPurchaseOrders")
    @ResponseBody
    public ResultVO addPurchaseOrders (String id){

        procurementPurchaseOrdersService.saveOrders(id);

        return ResultVOUtil.ok();
    }



}
